package com.dd.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.logistics.entity.Inventory;
import com.dd.logistics.entity.SupplierProduct;
import com.dd.logistics.mapper.SupplierProductMapper;
import com.dd.logistics.service.InventoryService;
import com.dd.logistics.service.ProductInventoryService;
import com.dd.logistics.service.SupplierProductService;
import com.dd.logistics.service.SupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SupplierProductServiceImpl extends ServiceImpl<SupplierProductMapper, SupplierProduct> implements SupplierProductService {
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    private ProductInventoryService productInventoryService;
    
    @Autowired
    private InventoryService inventoryService;
    
    @Override
    public List<SupplierProduct> getProductsBySupplierId(Long supplierId) {
        log.info("查询供应商商品列表，供应商ID：{}", supplierId);
        
        // 检查供应商是否存在
        checkSupplierExists(supplierId);
        
        // 构建查询条件
        QueryWrapper<SupplierProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("supplier_id", supplierId)
              .orderByDesc("create_time");
        
        // 执行查询
        List<SupplierProduct> list = baseMapper.selectList(wrapper);
        log.info("查询到{}条商品记录", list.size());
        return list;
    }
    
    @Override
    public Page<SupplierProduct> getProductsPage(Long supplierId, Integer current, Integer size, String productName) {
        log.info("分页查询供应商商品，供应商ID：{}，页码：{}，每页条数：{}，商品名称：{}", 
                supplierId, current, size, productName);
        
        // 检查供应商是否存在
        checkSupplierExists(supplierId);
        
        // 构建查询条件
        QueryWrapper<SupplierProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("supplier_id", supplierId);
        
        if (StringUtils.hasText(productName)) {
            wrapper.like("product_name", productName);
        }
        
        wrapper.orderByDesc("create_time");
        
        // 执行分页查询
        Page<SupplierProduct> page = new Page<>(current, size);
        return baseMapper.selectPage(page, wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProduct(SupplierProduct product) {
        log.info("添加商品，商品信息：{}", product);
        
        // 检查供应商是否存在
        checkSupplierExists(product.getSupplierId());
        
        // 检查商品编码是否已存在
        checkProductCodeExists(product, null);
        
        // 检查价格
        validatePrice(product.getPrice());
        
        // 设置默认状态
        product.setStatus(SupplierProduct.STATUS_ENABLED);
        // 确保设置商品名称
        if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
            throw new RuntimeException("商品名称不能为空");
        }
        
        boolean success = this.save(product);
        if (success) {
            log.info("添加商品成功，商品ID：{}", product.getId());
        } else {
            log.error("添加商品失败");
        }
        return success;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProduct(SupplierProduct product) {
        log.info("更新商品，商品信息：{}", product);
        
        // 检查商品是否存在
        SupplierProduct existingProduct = checkProductExists(product.getId());
        
        // 检查供应商是否存在
        checkSupplierExists(existingProduct.getSupplierId());
        
        // 检查商品编码是否已存在
        checkProductCodeExists(product, existingProduct);
        
        // 检查价格
        validatePrice(product.getPrice());
        
        // 不允许修改供应商ID
        product.setSupplierId(existingProduct.getSupplierId());
        
        boolean success = this.updateById(product);
        if (success) {
            log.info("更新商品成功，商品ID：{}", product.getId());
        } else {
            log.error("更新商品失败");
        }
        return success;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        log.info("更新商品状态，商品ID：{}，状态：{}", id, status);
        
        // 检查商品是否存在
        SupplierProduct existingProduct = checkProductExists(id);
        
        // 检查状态值是否有效
        if (status != SupplierProduct.STATUS_ENABLED && status != SupplierProduct.STATUS_DISABLED) {
            throw new RuntimeException("无效的状态值");
        }
        
        // 如果状态没有变化，直接返回成功
        if (existingProduct.getStatus().equals(status)) {
            String currentStatus = status == SupplierProduct.STATUS_ENABLED ? "启用" : "禁用";
            log.info("商品当前已经是{}状态，无需更新", currentStatus);
            return true;
        }
        
        // 更新状态
        SupplierProduct product = new SupplierProduct();
        product.setId(id);
        product.setStatus(status);
        
        boolean success = this.updateById(product);
        if (success) {
            String newStatus = status == SupplierProduct.STATUS_ENABLED ? "启用" : "禁用";
            log.info("商品状态更新成功，ID：{}，新状态：{}", id, newStatus);
        } else {
            log.error("商品状态更新失败，ID：{}，目标状态：{}", id, status);
        }
        
        return success;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Integer> batchUpdateStatus(List<Long> ids, Integer status) {
        log.info("批量更新商品状态，商品IDs：{}，目标状态：{}", ids, status);
        
        // 检查状态值是否有效
        if (status != SupplierProduct.STATUS_ENABLED && status != SupplierProduct.STATUS_DISABLED) {
            throw new RuntimeException("无效的状态值");
        }
        
        int successCount = 0;
        int failCount = 0;
        
        for (Long id : ids) {
            try {
                if (updateStatus(id, status)) {
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                log.error("更新商品状态失败，商品ID：{}，原因：{}", id, e.getMessage());
                failCount++;
            }
        }
        
        Map<String, Integer> result = new HashMap<>();
        result.put("total", ids.size());
        result.put("success", successCount);
        result.put("fail", failCount);
        
        log.info("批量更新商品状态完成，总数：{}，成功：{}，失败：{}", 
                ids.size(), successCount, failCount);
        
        return result;
    }
    
    @Override
    public Map<String, Integer> getStatusCount(Long supplierId) {
        log.info("查询供应商商品状态统计，供应商ID：{}", supplierId);
        
        // 检查供应商是否存在
        checkSupplierExists(supplierId);
        
        // 统计总数
        QueryWrapper<SupplierProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("sp.supplier_id", supplierId);
        int total = Math.toIntExact(baseMapper.selectCount(wrapper));
        
        // 统计启用数量
        wrapper.clear();
        wrapper.eq("sp.supplier_id", supplierId)
              .eq("sp.status", SupplierProduct.STATUS_ENABLED);
        int enabledCount = Math.toIntExact(baseMapper.selectCount(wrapper));
        
        // 统计禁用数量
        wrapper.clear();
        wrapper.eq("sp.supplier_id", supplierId)
              .eq("sp.status", SupplierProduct.STATUS_DISABLED);
        int disabledCount = Math.toIntExact(baseMapper.selectCount(wrapper));
        
        Map<String, Integer> result = new HashMap<>();
        result.put("total", total);
        result.put("enabled", enabledCount);
        result.put("disabled", disabledCount);
        
        log.info("查询供应商商品状态统计完成，总数：{}，启用：{}，禁用：{}", 
                total, enabledCount, disabledCount);
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> batchDelete(List<Long> ids) {
        log.info("批量删除商品，商品IDs：{}", ids);
        
        int successCount = 0;
        int failCount = 0;
        StringBuilder failIds = new StringBuilder();
        
        for (Long id : ids) {
            try {
                // 检查商品是否存在
                SupplierProduct product = checkProductExists(id);
                
                if (this.removeById(id)) {
                    successCount++;
                    log.info("删除商品成功，商品ID：{}", id);
                } else {
                    failCount++;
                    failIds.append(id).append(",");
                    log.error("删除商品失败，商品ID：{}", id);
                }
            } catch (Exception e) {
                failCount++;
                failIds.append(id).append(",");
                log.error("删除商品失败，商品ID：{}，原因：{}", id, e.getMessage());
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", ids.size());
        result.put("success", successCount);
        result.put("fail", failCount);
        
        String failIdsStr = failIds.toString();
        if (!failIdsStr.isEmpty()) {
            result.put("failIds", failIdsStr.substring(0, failIdsStr.length() - 1));
        }
        
        log.info("批量删除商品完成，总数：{}，成功：{}，失败：{}", 
                ids.size(), successCount, failCount);
        
        return result;
    }
    
    @Override
    public Page<SupplierProduct> search(Long supplierId, String productCode, String productName, 
            Integer status, Integer current, Integer size) {
        log.info("搜索商品，供应商ID：{}，商品编码：{}，商品名称：{}，状态：{}，页码：{}，每页条数：{}", 
                supplierId, productCode, productName, status, current, size);
        
        // 构建查询条件
        QueryWrapper<SupplierProduct> wrapper = new QueryWrapper<>();
        if (supplierId != null) {
            wrapper.eq("supplier_id", supplierId);
        }
        if (StringUtils.hasText(productCode)) {
            wrapper.like("product_code", productCode.trim());
        }
        if (StringUtils.hasText(productName)) {
            wrapper.like("product_name", productName.trim());
        }
        if (status != null) {
            wrapper.eq("status", status);
        }
        wrapper.orderByDesc("create_time");
        
        // 执行分页查询
        Page<SupplierProduct> page = new Page<>(current, size);
        return baseMapper.selectPage(page, wrapper);
    }
    
    /**
     * 检查供应商是否存在
     */
    private void checkSupplierExists(Long supplierId) {
        if (!supplierService.checkSupplierExists(supplierId)) {
            throw new RuntimeException("供应商不存在");
        }
    }
    
    /**
     * 检查商品是否存在
     */
    private SupplierProduct checkProductExists(Long productId) {
        SupplierProduct product = baseMapper.selectById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        return product;
    }
    
    /**
     * 检查商品编码是否已存在
     */
    private void checkProductCodeExists(SupplierProduct product, SupplierProduct existingProduct) {
        QueryWrapper<SupplierProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("supplier_id", product.getSupplierId())
              .eq("product_code", product.getProductCode());
        
        if (existingProduct != null) {
            wrapper.ne("id", existingProduct.getId());
        }
        
        Long count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new RuntimeException("该供应商下商品编码已存在");
        }
    }
    
    /**
     * 验证价格
     */
    private void validatePrice(BigDecimal price) {
        if (price != null && price.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("商品价格不能小于0");
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        try {
            // 1. 先删除相关的库存记录
            QueryWrapper<Inventory> inventoryWrapper = new QueryWrapper<>();
            inventoryWrapper.eq("product_id", id);
            inventoryService.remove(inventoryWrapper);
            
            // 2. 删除商品记录
            return super.removeById(id);
        } catch (Exception e) {
            log.error("删除商品失败，ID：{}，异常：{}", id, e.getMessage());
            throw new RuntimeException("删除商品失败：" + e.getMessage());
        }
    }
    
    @Override
    public SupplierProduct getProductDetail(Long id) {
        log.info("查询商品详情，商品ID：{}", id);
        
        try {
            // 使用关联查询获取商品信息
            QueryWrapper<SupplierProduct> wrapper = new QueryWrapper<>();
            wrapper.eq("sp.id", id);
            List<SupplierProduct> products = baseMapper.selectProductsWithName(wrapper);
            
            if (products == null || products.isEmpty()) {
                log.warn("商品不存在，商品ID：{}", id);
                return null;
            }
            
            SupplierProduct product = products.get(0);
            log.info("查询商品详情成功，商品ID：{}", id);
            return product;
        } catch (Exception e) {
            log.error("查询商品详情失败，商品ID：{}，原因：{}", id, e.getMessage());
            throw new RuntimeException("查询商品详情失败：" + e.getMessage());
        }
    }
} 